'use client';

import React, { useState } from 'react';
import Button from '@/components/ui/Button';
import { 
  Plus,
  Search,
  Download,
  Upload,
  Eye,
  Database,
  Server,
  Activity,
  Clock,
  HardDrive,
  Users,
  BarChart3,
  ArrowRight,
  CheckCircle,
  AlertCircle,
  Archive,
  Layers,
  Settings
} from 'lucide-react';

// 节点信息接口
interface Node {
  id: string;
  name: string;
  services: ('设备运检I' | '人员安全' | '环境巡视' | '设备运检S')[];
  deployedModelId: string;
  collectedSamples: number;
  uncollectedSamples: number;
  lastCollectionTime: string;
  status: 'online' | 'offline' | 'syncing';
}

// 数据集信息接口
interface Dataset {
  id: number;
  dataset_id: string;
  name: string;
  uploader: string;
  is_learned: boolean;
  data_size: string;
  upload_time: string;
  is_annotated: boolean;
  data_format: string;
  sample_count: number;
  time_range: string;
  update_frequency: string;
  is_forgetting: boolean;
  is_quantization: boolean;
  is_incremental: boolean;
  is_base: boolean;
  folder_path: string;
  created_at: string;
  updated_at: string;
  scenario: string; // 电力场景
}

export default function SamplesPage() {
  const [activeTab, setActiveTab] = useState<'datasets' | 'nodes'>('datasets');
  
  // 模拟数据集数据
  const [datasets] = useState<Dataset[]>([
    {
      id: 1,
      dataset_id: 'power-base-001',
      name: '变电站设备监控基础数据集',
      uploader: '系统管理员',
      is_learned: true,
      data_size: '2.3GB',
      upload_time: '2024-01-15',
      is_annotated: true,
      data_format: 'IMAGE',
      sample_count: 15680,
      time_range: '2023-2024年',
      update_frequency: '每日',
      is_forgetting: false,
      is_quantization: true,
      is_incremental: false,
      is_base: true,
      folder_path: '/datasets/power-base-001',
      created_at: '2024-01-15T08:00:00Z',
      updated_at: '2024-12-03T10:30:00Z',
      scenario: '变电站监控'
    },
    {
      id: 2,
      dataset_id: 'power-trans-002',
      name: '输电线路巡检基础数据集',
      uploader: '运维团队',
      is_learned: true,
      data_size: '1.8GB',
      upload_time: '2024-02-20',
      is_annotated: true,
      data_format: 'IMAGE',
      sample_count: 12450,
      time_range: '2023-2024年',
      update_frequency: '每周',
      is_forgetting: false,
      is_quantization: false,
      is_incremental: false,
      is_base: true,
      folder_path: '/datasets/power-trans-002',
      created_at: '2024-02-20T09:00:00Z',
      updated_at: '2024-12-02T14:20:00Z',
      scenario: '输电线路巡检'
    },
    {
      id: 3,
      dataset_id: 'power-dist-003',
      name: '配电网智能运维基础数据集',
      uploader: '配电部门',
      is_learned: false,
      data_size: '950MB',
      upload_time: '2024-03-10',
      is_annotated: true,
      data_format: 'IMAGE',
      sample_count: 8320,
      time_range: '2024年',
      update_frequency: '每月',
      is_forgetting: true,
      is_quantization: false,
      is_incremental: true,
      is_base: true,
      folder_path: '/datasets/power-dist-003',
      created_at: '2024-03-10T11:00:00Z',
      updated_at: '2024-11-28T16:45:00Z',
      scenario: '配电网运维'
    },
    {
      id: 4,
      dataset_id: 'power-user-004',
      name: '用户侧智能电表基础数据集',
      uploader: '用户服务部',
      is_learned: true,
      data_size: '1.2GB',
      upload_time: '2024-04-05',
      is_annotated: false,
      data_format: 'SEQUENCE',
      sample_count: 25600,
      time_range: '2023-2024年',
      update_frequency: '每日',
      is_forgetting: false,
      is_quantization: true,
      is_incremental: false,
      is_base: true,
      folder_path: '/datasets/power-user-004',
      created_at: '2024-04-05T07:30:00Z',
      updated_at: '2024-12-03T09:15:00Z',
      scenario: '用户侧监控'
    },
    {
      id: 5,
      dataset_id: 'power-incr-005',
      name: '新增缺陷样本增量数据集',
      uploader: '质量控制组',
      is_learned: false,
      data_size: '180MB',
      upload_time: '2024-12-01',
      is_annotated: true,
      data_format: 'IMAGE',
      sample_count: 1240,
      time_range: '2024年11月',
      update_frequency: '实时',
      is_forgetting: false,
      is_quantization: false,
      is_incremental: true,
      is_base: false,
      folder_path: '/datasets/power-incr-005',
      created_at: '2024-12-01T13:20:00Z',
      updated_at: '2024-12-03T11:00:00Z',
      scenario: '变电站监控'
    }
  ]);

  // 模拟节点数据
  const [nodes] = useState<Node[]>([
    {
      id: 'node-001',
      name: '变电站A-边缘节点',
      services: ['设备运检S', '设备运检I'],
      deployedModelId: 'PowerNet-Defect-v1.8.2',
      collectedSamples: 1580,
      uncollectedSamples: 320,
      lastCollectionTime: '2024-12-03T08:30:00Z',
      status: 'online'
    },
    {
      id: 'node-002',
      name: '输电塔B-监控终端',
      services: ['设备运检S', '设备运检I'],
      deployedModelId: 'PowerVision-Workers-v2.3.1',
      collectedSamples: 2340,
      uncollectedSamples: 180,
      lastCollectionTime: '2024-12-03T09:15:00Z',
      status: 'online'
    },
    {
      id: 'node-003',
      name: '配电房C-智能网关',
      services: ['设备运检I'],
      deployedModelId: 'PowerSeq-Defect-v2.1.3',
      collectedSamples: 890,
      uncollectedSamples: 450,
      lastCollectionTime: '2024-12-02T16:20:00Z',
      status: 'syncing'
    },
    {
      id: 'node-004',
      name: '用户端D-采集器',
      services: ['设备运检I'],
      deployedModelId: 'PowerNet-Defect-v1.8.2',
      collectedSamples: 650,
      uncollectedSamples: 95,
      lastCollectionTime: '2024-12-01T14:45:00Z',
      status: 'offline'
    }
  ]);

  const [searchTerm, setSearchTerm] = useState('');
  const [datasetFilter, setDatasetFilter] = useState('all');
  const [nodeFilter, setNodeFilter] = useState('all');

  // 数据集状态徽章
  const getDatasetStatusBadge = (dataset: Dataset) => {
    if (!dataset.is_base) {
      return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 border border-blue-200">
        <span className="w-1.5 h-1.5 bg-blue-600 rounded-full mr-1.5"></span>
        增量数据
      </span>;
    }
    
    if (dataset.is_learned) {
      return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800 border border-green-200">
        <span className="w-1.5 h-1.5 bg-green-600 rounded-full mr-1.5"></span>
        已学习
      </span>;
    }
    
    return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800 border border-yellow-200">
      <span className="w-1.5 h-1.5 bg-yellow-600 rounded-full mr-1.5"></span>
      待学习
    </span>;
  };

  // 节点状态徽章
  const getNodeStatusBadge = (status: string) => {
    switch (status) {
      case 'online':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800 border border-green-200">
          <span className="w-1.5 h-1.5 bg-green-600 rounded-full mr-1.5"></span>
          在线
        </span>;
      case 'offline':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800 border border-red-200">
          <span className="w-1.5 h-1.5 bg-red-600 rounded-full mr-1.5"></span>
          离线
        </span>;
      case 'syncing':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 border border-blue-200">
          <span className="w-1.5 h-1.5 bg-blue-600 rounded-full mr-1.5"></span>
          同步中
        </span>;
      default:
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800 border border-gray-200">
          {status}
        </span>;
    }
  };

  // 过滤数据集
  const filteredDatasets = datasets.filter(dataset => {
    return (
      (searchTerm === '' || dataset.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      dataset.dataset_id.toLowerCase().includes(searchTerm.toLowerCase())) &&
      (datasetFilter === 'all' || 
       (datasetFilter === 'base' && dataset.is_base) ||
       (datasetFilter === 'incremental' && !dataset.is_base) ||
       (datasetFilter === 'learned' && dataset.is_learned) ||
       (datasetFilter === 'unlearned' && !dataset.is_learned))
    );
  });

  // 过滤节点
  const filteredNodes = nodes.filter(node => {
    return (
      (searchTerm === '' || node.name.toLowerCase().includes(searchTerm.toLowerCase())) &&
      (nodeFilter === 'all' || node.status === nodeFilter)
    );
  });

  // 统计数据
  const stats = {
    totalDatasets: datasets.length,
    baseDatasets: datasets.filter(d => d.is_base).length,
    incrementalDatasets: datasets.filter(d => !d.is_base).length,
    learnedDatasets: datasets.filter(d => d.is_learned).length,
    totalSamples: datasets.reduce((sum, d) => sum + d.sample_count, 0),
    onlineNodes: nodes.filter(n => n.status === 'online').length,
    totalNodes: nodes.length,
    uncollectedSamples: nodes.reduce((sum, n) => sum + n.uncollectedSamples, 0),
    collectedSamples: nodes.reduce((sum, n) => sum + n.collectedSamples, 0)
  };

  return (
    <div className="space-y-4">
      {/* 标题栏 */}
      <div className="flex items-center justify-between rounded-lg px-4 py-3">
        <div>
          <h1 className="text-xl font-bold text-gray-900">样本数据管理</h1>
          <p className="text-sm text-gray-600 mt-0.5">数据集管理与边缘节点数据归集</p>
        </div>
        <div className="flex gap-2">
          <Button variant="secondary" size="sm">
            <Upload className="h-4 w-4 mr-1.5" />
            数据导入
          </Button>
          <Button variant="primary" size="sm">
            <Plus className="h-4 w-4 mr-1.5" />
            新建数据集
          </Button>
        </div>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
        <div className="bg-gray-50 border border-gray-200 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-xs font-medium text-blue-700 uppercase tracking-wide">基础数据集</div>
              <div className="text-2xl text-blue-700 font-bold mt-1">{stats.baseDatasets}</div>
            </div>
            <Database className="h-6 w-6 text-blue-600" />
          </div>
        </div>
        
        <div className="bg-gray-50 border border-gray-200 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-xs font-medium text-green-700 uppercase tracking-wide">已学习</div>
              <div className="text-2xl text-green-700 font-bold mt-1">{stats.learnedDatasets}</div>
            </div>
            <CheckCircle className="h-6 w-6 text-green-600" />
          </div>
        </div>
        
        <div className="bg-gray-50 border border-gray-200 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-xs font-medium text-purple-700 uppercase tracking-wide">在线节点</div>
              <div className="text-2xl text-purple-700 font-bold mt-1">{stats.onlineNodes}/{stats.totalNodes}</div>
            </div>
            <Server className="h-6 w-6 text-purple-600" />
          </div>
        </div>
        
        <div className="bg-gray-50 border border-gray-200 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-xs font-medium text-orange-700 uppercase tracking-wide">待归集样本</div>
              <div className="text-2xl text-orange-700 font-bold mt-1">{stats.uncollectedSamples.toLocaleString()}</div>
            </div>
            <AlertCircle className="h-6 w-6 text-orange-600" />
          </div>
        </div>
      </div>

      {/* 标签页切换 */}
      <div className="bg-white border border-gray-200 rounded-lg shadow-sm">
        <div className="border-b border-gray-200">
          <nav className="flex">
            <button
              onClick={() => setActiveTab('datasets')}
              className={`px-6 py-3 text-sm font-medium border-b-2 ${
                activeTab === 'datasets'
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              }`}
            >
              <Database className="h-4 w-4 inline mr-2" />
              数据集总览
            </button>
            <button
              onClick={() => setActiveTab('nodes')}
              className={`px-6 py-3 text-sm font-medium border-b-2 ${
                activeTab === 'nodes'
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              }`}
            >
              <Server className="h-4 w-4 inline mr-2" />
              节点数据归集
            </button>
          </nav>
        </div>

        {/* 搜索栏 */}
        <div className="px-4 py-3 border-b border-gray-200">
          <div className="flex flex-col sm:flex-row gap-3">
            <div className="flex-1">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
                <input
                  type="text"
                  placeholder={activeTab === 'datasets' ? "搜索数据集名称或ID..." : "搜索节点名称..."}
                  className="w-full pl-10 pr-4 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                />
              </div>
            </div>
            <div className="flex gap-3">
              {activeTab === 'datasets' ? (
                <select
                  className="px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  value={datasetFilter}
                  onChange={(e) => setDatasetFilter(e.target.value)}
                >
                  <option value="all">全部数据集</option>
                  <option value="base">基础数据集</option>
                  <option value="incremental">增量数据集</option>
                  <option value="learned">已学习</option>
                  <option value="unlearned">待学习</option>
                </select>
              ) : (
                <select
                  className="px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  value={nodeFilter}
                  onChange={(e) => setNodeFilter(e.target.value)}
                >
                  <option value="all">全部状态</option>
                  <option value="online">在线</option>
                  <option value="offline">离线</option>
                  <option value="syncing">同步中</option>
                </select>
              )}
            </div>
          </div>
        </div>

        {/* 内容区域 */}
        <div className="overflow-x-auto">
          {activeTab === 'datasets' ? (
            // 数据集表格
            <table className="min-w-full divide-y divide-gray-200">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">数据集信息</th>
                  <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                  <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">格式</th>
                  <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">样本数量</th>
                  <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">大小</th>
                  <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">特性</th>
                  <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">更新时间</th>
                  <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {filteredDatasets.map((dataset) => (
                  <tr key={dataset.id} className="hover:bg-gray-50 transition-colors">
                    <td className="px-4 py-3">
                      <div className="min-w-0">
                        <div className="text-sm font-medium text-gray-900 truncate">{dataset.name}</div>
                        <div className="text-xs text-gray-500 truncate mt-1">ID: {dataset.dataset_id}</div>
                        <div className="text-xs text-gray-400 mt-1">
                          <span className="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-gray-100 text-gray-800">
                            {dataset.scenario}
                          </span>
                          <span className="ml-2">上传者: {dataset.uploader}</span>
                        </div>
                      </div>
                    </td>
                    <td className="px-4 py-3 text-center">
                      {getDatasetStatusBadge(dataset)}
                    </td>
                    <td className="px-4 py-3 text-center">
                      <span className="inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium bg-indigo-100 text-indigo-800">
                        {dataset.data_format}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-center">
                      <div className="text-sm font-medium text-gray-900">{dataset.sample_count.toLocaleString()}</div>
                      <div className="text-xs text-gray-500">{dataset.time_range}</div>
                    </td>
                    <td className="px-4 py-3 text-center">
                      <div className="flex items-center justify-center">
                        <HardDrive className="h-3 w-3 text-gray-400 mr-1" />
                        <span className="text-sm font-medium text-gray-900">{dataset.data_size}</span>
                      </div>
                    </td>
                    <td className="px-4 py-3 text-center">
                      <div className="flex flex-wrap gap-1 justify-center">
                        {dataset.is_base && (
                          <span className="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800">基础</span>
                        )}
                        {dataset.is_incremental && (
                          <span className="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800">增量</span>
                        )}
                        {dataset.is_annotated && (
                          <span className="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-purple-100 text-purple-800">已标注</span>
                        )}
                        {dataset.is_quantization && (
                          <span className="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-orange-100 text-orange-800">量化</span>
                        )}
                      </div>
                    </td>
                    <td className="px-4 py-3 text-center">
                      <div className="text-xs text-gray-500">
                        {new Date(dataset.updated_at).toLocaleDateString()}
                      </div>
                    </td>
                    <td className="px-4 py-3 text-center">
                      <div className="flex items-center justify-center gap-1">
                        <Button size="sm" variant="secondary">
                          <Eye className="h-3 w-3" />
                        </Button>
                        <Button size="sm" variant="secondary">
                          <Download className="h-3 w-3" />
                        </Button>
                        <Button size="sm" variant="secondary">
                          <Settings className="h-3 w-3" />
                        </Button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          ) : (
            // 节点表格
            <table className="min-w-full divide-y divide-gray-200">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">节点信息</th>
                  <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                  <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">运行服务</th>
                  <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">部署模型</th>
                  <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">样本统计</th>
                  <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">最后归集</th>
                  <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {filteredNodes.map((node) => (
                  <tr key={node.id} className="hover:bg-gray-50 transition-colors">
                    <td className="px-4 py-3">
                      <div className="min-w-0">
                        <div className="text-sm font-medium text-gray-900 truncate">{node.name}</div>
                        <div className="text-xs text-gray-500 truncate mt-1">ID: {node.id}</div>
                      </div>
                    </td>
                    <td className="px-4 py-3 text-center">
                      {getNodeStatusBadge(node.status)}
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex flex-wrap gap-1">
                        {node.services.map((service, index) => (
                          <span key={index} className="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800">
                            {service}
                          </span>
                        ))}
                      </div>
                    </td>
                    <td className="px-4 py-3 text-center">
                      <span className="inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium bg-indigo-100 text-indigo-800">
                        {node.deployedModelId}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-center">
                      <div className="text-sm">
                        <div className="flex items-center justify-center text-green-600 font-medium">
                          <CheckCircle className="h-3 w-3 mr-1" />
                          {node.collectedSamples.toLocaleString()}
                        </div>
                        <div className="flex items-center justify-center text-orange-600 font-medium mt-1">
                          <AlertCircle className="h-3 w-3 mr-1" />
                          {node.uncollectedSamples.toLocaleString()}
                        </div>
                      </div>
                    </td>
                    <td className="px-4 py-3 text-center">
                      <div className="text-xs text-gray-500">
                        {new Date(node.lastCollectionTime).toLocaleString()}
                      </div>
                    </td>
                    <td className="px-4 py-3 text-center">
                      <div className="flex items-center justify-center gap-1">
                        <Button 
                          size="sm" 
                          variant="primary"
                          disabled={node.status === 'offline' || node.uncollectedSamples === 0}
                        >
                          <ArrowRight className="h-3 w-3 mr-1" />
                          归集
                        </Button>
                        <Button size="sm" variant="secondary">
                          <Eye className="h-3 w-3" />
                        </Button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>

        {/* 底部统计 */}
        <div className="border-t border-gray-200 bg-gray-50 px-4 py-3">
          <div className="flex items-center justify-between text-sm text-gray-600">
            {activeTab === 'datasets' ? (
              <>
                <div className="flex items-center gap-6">
                  <span>共 {stats.totalDatasets} 个数据集</span>
                  <span>基础数据集: {stats.baseDatasets}</span>
                  <span>增量数据集: {stats.incrementalDatasets}</span>
                </div>
                <div className="flex items-center gap-6">
                  <span>总样本数: {stats.totalSamples.toLocaleString()}</span>
                  <span>已学习: {stats.learnedDatasets}</span>
                </div>
              </>
            ) : (
              <>
                <div className="flex items-center gap-6">
                  <span>共 {stats.totalNodes} 个节点</span>
                  <span>在线: {stats.onlineNodes}</span>
                  <span>离线: {stats.totalNodes - stats.onlineNodes}</span>
                </div>
                <div className="flex items-center gap-6">
                  <span>已归集: {stats.collectedSamples.toLocaleString()}</span>
                  <span>待归集: {stats.uncollectedSamples.toLocaleString()}</span>
                </div>
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
